//
//  WYJComposeView.swift
//  MySinaWeibo
//
//  Created by eastriver on 17/3/28.
//  Copyright © 2017年 believewilliam. All rights reserved.
//

import UIKit
import pop
class WYJComposeView: UIView {
   // 按钮数组
    private lazy var buttonArray: [WYJComposeTypeButton] = [WYJComposeTypeButton]()
    // 记录其被添加到哪个控制器的view中
    var locatedVC: UIViewController?
   // 重写构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
       
        setupUI()
    }
    private func setupUI() {
        // 添加以当前屏幕截图为image的imageView
        let snapShotImgV = UIImageView(image: UIImage.snapShotForCurrentScreen()?.applyLightEffect())
        addSubview(snapShotImgV)
        // 添加sloganImgV
        let sloganImgV = UIImageView(image: #imageLiteral(resourceName: "compose_slogan"))
        addSubview(sloganImgV)
        // 设置约束
        sloganImgV.snp.makeConstraints { (make) in
            make.centerX.equalTo(self)
            make.top.equalTo(self).offset(100)
        }
        // 添加6个button
        addChildButtons()
    }
    
    private func addChildButtons() {
        
        let margin: CGFloat = (screenWidth - 3 * btnW) / (3 + 1)
        for i in 0..<6 {
            let btn = WYJComposeTypeButton()
//            btn.backgroundColor = UIColor.red
            btn.setTitle("位置", for: .normal)
            btn.setImage(#imageLiteral(resourceName: "tabbar_compose_lbs"), for: .normal)
            // 设置frame
            let columnIndex = i % 3
            let rowIndex = i / 3
            let btnX = margin + (btnW + margin) * CGFloat(columnIndex)
            let btnY = (btnH + margin) * CGFloat(rowIndex) + screenHeight
            btn.frame = CGRect(x: btnX, y: btnY, width: btnW, height: btnH)
            // 添加点击事件
            btn.addTarget(self, action: #selector(composeTypeButtonDidClick(btn:)), for: .touchUpInside)
            addSubview(btn)
            buttonArray.append(btn)
        }
    }
    // 给按钮添加弹出动画
    override func willMove(toSuperview newSuperview: UIView?) {
        for value in buttonArray.enumerated() {
            composeButtonStartAnimation(btn: value.element, index: value.offset)
        }
        
    }
    // 给按钮添加消失的动画
    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        for value in buttonArray.reversed().enumerated() {
            composeButtonStartAnimation(btn: value.element, index: value.offset, isUp: false)
        }
        DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
            self.removeFromSuperview()
        }
    }
    // 封装6个button的动画
    private func composeButtonStartAnimation(btn: WYJComposeTypeButton, index: Int, isUp: Bool = true) {
       
            // 添加动画效果
            let ani = POPSpringAnimation(propertyNamed: kPOPViewCenter)
            ani?.springBounciness = 10
            ani?.springSpeed = 12
            ani?.beginTime = CACurrentMediaTime() + Double(index) * 0.025
            // 下面设置toValue属性时，我不明白为什么为使用NSValue进行类型转换。但是，不转换确实会崩溃。
            ani?.toValue = NSValue(cgPoint: CGPoint(x: btn.center.x, y: btn.center.y + (isUp ? -350 : 350)))
            btn.pop_add(ani, forKey: nil)

    }
    // 点击composeButton后系统调用的方法：先动画，然后转到模态视图
    @objc private func composeTypeButtonDidClick(btn: WYJComposeTypeButton) {
        // 动画
        for btnELement in buttonArray {
            btnELement.alpha = 0.1
            if btn == btnELement {
                // 放大动画
                UIView.animate(withDuration: 0.5, animations: { 
                    btn.transform = CGAffineTransform(scaleX: 2, y: 2)
                    }, completion: { (_) in
                        // 模态视图
                        // 假设模态视图的类是由服务器配置的，假设下行代码获得了模态视图的类
                        let productName = Bundle.main.infoDictionary!["CFBundleName"] as! String
                        let classString = productName + "." + "WYJComposeViewController"
                        let classType = NSClassFromString(classString) as! UIViewController.Type
                        let targetVC = classType.init()
                        let navgationVC = UINavigationController(rootViewController: targetVC)
                        self.locatedVC?.present(navgationVC, animated: true, completion: {
                            self.removeFromSuperview()
                        })
                })
            } else {
                // 缩小动画
                UIView.animate(withDuration: 0.5, animations: { 
                    btnELement.transform = CGAffineTransform(scaleX: 0.1, y: 0.1)
                })
            }
        }
    }

    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}
